import api from './api'
import type {
  CoreMetricsDto,
  StatisticsQueryDto,
  StatisticsDto,
  PagedResultDto,
  AnnouncementQueryDto,
  AnnouncementDto,
  PurchaseOrderQueryDto,
  PurchaseOrderDto,
  PurchaseOrderExtendedDto,
  PurchaseOrderExtendedQueryDto,
  ApprovalDecisionDto,
  ApprovalFlowDto,
  ProductionOrderQueryDto,
  ProductionOrderDto,
  ProductionSalesOrderQueryDto,
  ProductionSalesOrderDto,
  ApprovalDocumentQueryDto,
  ApprovalDocumentDto,
  WarehouseQueryDto,
  WarehouseDto,
  ProductionItemQueryDto,
  ProductionItemDto,
  ProcessQueryDto,
  ProcessDto,
  ChartDataDto
} from '@/types/console'
import type { ApiResult } from '@/types/auth'

// 控制台API服务
export const consoleApi = {
  // 获取今日核心指标
  async getTodayMetrics(): Promise<ApiResult<CoreMetricsDto>> {
    try {
      const response = await api.get('/Dashboard/today-metrics')
      return response.data
    } catch (error: any) {
      console.error('获取今日核心指标失败:', error)
      return {
        msg: '获取今日核心指标失败',
        code: 500,
        data: {} as CoreMetricsDto
      }
    }
  },

  // 获取核心指标数据
  async getCoreMetrics(startDate?: string, endDate?: string): Promise<ApiResult<CoreMetricsDto[]>> {
    try {
      const params = new URLSearchParams()
      if (startDate) params.append('startDate', startDate)
      if (endDate) params.append('endDate', endDate)

      const response = await api.get(`/Dashboard/core-metrics?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取核心指标数据失败:', error)
      return {
        msg: '获取核心指标数据失败',
        code: 500,
        data: []
      }
    }
  },

  // 获取统计数据
  async getStatistics(query: StatisticsQueryDto): Promise<ApiResult<StatisticsDto[]>> {
    try {
      const params = new URLSearchParams()
      if (query.startDate) params.append('startDate', query.startDate)
      if (query.endDate) params.append('endDate', query.endDate)
      if (query.type) params.append('type', query.type)
      if (query.timeRange) params.append('timeRange', query.timeRange)

      const response = await api.get(`/Dashboard/statistics?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取统计数据失败:', error)
      return {
        msg: '获取统计数据失败',
        code: 500,
        data: []
      }
    }
  },

  // 获取销售统计图表数据
  async getSalesChartData(timeRange: string = 'week'): Promise<ApiResult<ChartDataDto>> {
    try {
      const response = await api.get(`/Dashboard/sales-chart?timeRange=${timeRange}`)
      return response.data
    } catch (error: any) {
      console.error('获取销售图表数据失败:', error)
      return {
        msg: '获取销售图表数据失败',
        code: 500,
        data: {} as ChartDataDto
      }
    }
  },

  // 获取采购统计图表数据
  async getPurchaseChartData(timeRange: string = 'week'): Promise<ApiResult<ChartDataDto>> {
    try {
      const response = await api.get(`/Dashboard/purchase-chart?timeRange=${timeRange}`)
      return response.data
    } catch (error: any) {
      console.error('获取采购图表数据失败:', error)
      return {
        msg: '获取采购图表数据失败',
        code: 500,
        data: {} as ChartDataDto
      }
    }
  },

  // 获取通知公告列表
  async getAnnouncements(query: AnnouncementQueryDto): Promise<ApiResult<PagedResultDto<AnnouncementDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.type) params.append('type', query.type)
      if (query.isActive !== undefined) params.append('isActive', query.isActive.toString())

      const response = await api.get(`/Announcement?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取通知公告列表失败:', error)
      return {
        msg: '获取通知公告列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取审批单据列表
  async getApprovalDocuments(query: ApprovalDocumentQueryDto): Promise<ApiResult<PagedResultDto<ApprovalDocumentDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.documentType) params.append('documentType', query.documentType)
      if (query.status) params.append('status', query.status)

      const response = await api.get(`/ApprovalDocument?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取审批单据列表失败:', error)
      return {
        msg: '获取审批单据列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取采购订单列表
  async getPurchaseOrders(query: PurchaseOrderQueryDto): Promise<ApiResult<PagedResultDto<PurchaseOrderDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.orderType) params.append('orderType', query.orderType)

      const response = await api.get(`/Dashboard/purchase-orders?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取采购订单列表失败:', error)
      return {
        msg: '获取采购订单列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取生产工单列表
  async getProductionOrders(query: ProductionOrderQueryDto): Promise<ApiResult<PagedResultDto<ProductionOrderDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.responsiblePerson) params.append('responsiblePerson', query.responsiblePerson)

      const response = await api.get(`/Dashboard/production-orders?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取生产工单列表失败:', error)
      return {
        msg: '获取生产工单列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取销售订单列表
  async getSalesOrders(query: ProductionSalesOrderQueryDto): Promise<ApiResult<PagedResultDto<ProductionSalesOrderDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.customerName) params.append('customerName', query.customerName)

      const response = await api.get(`/Dashboard/sales-orders?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取销售订单列表失败:', error)
      return {
        msg: '获取销售订单列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取仓库列表
  async getWarehouses(query: WarehouseQueryDto): Promise<ApiResult<PagedResultDto<WarehouseDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.warehouseType) params.append('warehouseType', query.warehouseType)
      if (query.status) params.append('status', query.status)

      const response = await api.get(`/Warehouse?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取仓库列表失败:', error)
      return {
        msg: '获取仓库列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取生产物品列表
  async getProductionItems(query: ProductionItemQueryDto): Promise<ApiResult<PagedResultDto<ProductionItemDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.itemType) params.append('itemType', query.itemType)
      if (query.warehouseId) params.append('warehouseId', query.warehouseId.toString())

      const response = await api.get(`/ProductionItem?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取生产物品列表失败:', error)
      return {
        msg: '获取生产物品列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取工序列表
  async getProcesses(query: ProcessQueryDto): Promise<ApiResult<PagedResultDto<ProcessDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.processType) params.append('processType', query.processType)

      const response = await api.get(`/Process?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取工序列表失败:', error)
      return {
        msg: '获取工序列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // === 采购订单管理 ===

  // 获取采购订单详情
  async getPurchaseOrderDetail(id: number): Promise<ApiResult<PurchaseOrderDto>> {
    try {
      const response = await api.get(`/PurchaseOrder/${id}`)
      return response.data
    } catch (error: any) {
      console.error('获取采购订单详情失败:', error)
      return {
        msg: '获取采购订单详情失败',
        code: 500,
        data: {} as PurchaseOrderDto
      }
    }
  },

  // 创建采购订单
  async createPurchaseOrder(data: PurchaseOrderDto): Promise<ApiResult<PurchaseOrderDto>> {
    try {
      const response = await api.post('/PurchaseOrder', data)
      return response.data
    } catch (error: any) {
      console.error('创建采购订单失败:', error)
      return {
        msg: '创建采购订单失败',
        code: 500,
        data: {} as PurchaseOrderDto
      }
    }
  },

  // 更新采购订单
  async updatePurchaseOrder(data: PurchaseOrderDto): Promise<ApiResult<PurchaseOrderDto>> {
    try {
      const response = await api.put('/PurchaseOrder', data)
      return response.data
    } catch (error: any) {
      console.error('更新采购订单失败:', error)
      return {
        msg: '更新采购订单失败',
        code: 500,
        data: {} as PurchaseOrderDto
      }
    }
  },

  // 删除采购订单
  async deletePurchaseOrder(id: number): Promise<ApiResult<boolean>> {
    try {
      const response = await api.delete(`/PurchaseOrder/${id}`)
      return response.data
    } catch (error: any) {
      console.error('删除采购订单失败:', error)
      return {
        msg: '删除采购订单失败',
        code: 500,
        data: false
      }
    }
  },

  // === 扩展采购订单管理 ===

  // 获取扩展采购订单列表
  async getPurchaseOrdersExtended(query: PurchaseOrderExtendedQueryDto): Promise<ApiResult<PagedResultDto<PurchaseOrderExtendedDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.orderType) params.append('orderType', query.orderType)
      if (query.creator) params.append('creator', query.creator)
      if (query.createStartTime) params.append('createStartTime', query.createStartTime)
      if (query.createEndTime) params.append('createEndTime', query.createEndTime)
      if (query.minAmount) params.append('minAmount', query.minAmount.toString())
      if (query.maxAmount) params.append('maxAmount', query.maxAmount.toString())
      params.append('includeApprovalFlow', query.includeApprovalFlow.toString())

      const response = await api.get(`/PurchaseOrder/extended?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取扩展采购订单列表失败:', error)
      return {
        msg: '获取扩展采购订单列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取扩展采购订单详情
  async getPurchaseOrderExtendedDetail(id: number): Promise<ApiResult<PurchaseOrderExtendedDto>> {
    try {
      console.log('API: 请求扩展订单详情，URL:', `/PurchaseOrder/extended/${id}`)
      const response = await api.get(`/PurchaseOrder/extended/${id}`)
      console.log('API: 响应数据:', response.data)
      return response.data
    } catch (error: any) {
      console.error('获取扩展采购订单详情失败:', error)
      return {
        msg: '获取扩展采购订单详情失败',
        code: 500,
        data: {} as PurchaseOrderExtendedDto
      }
    }
  },

  // 创建扩展采购订单
  async createPurchaseOrderExtended(data: PurchaseOrderExtendedDto): Promise<ApiResult<PurchaseOrderExtendedDto>> {
    try {
      const response = await api.post('/PurchaseOrder/extended', data)
      return response.data
    } catch (error: any) {
      console.error('创建扩展采购订单失败:', error)
      return {
        msg: '创建扩展采购订单失败',
        code: 500,
        data: {} as PurchaseOrderExtendedDto
      }
    }
  },

  // 更新扩展采购订单
  async updatePurchaseOrderExtended(data: PurchaseOrderExtendedDto): Promise<ApiResult<PurchaseOrderExtendedDto>> {
    try {
      const response = await api.put('/PurchaseOrder/extended', data)
      return response.data
    } catch (error: any) {
      console.error('更新扩展采购订单失败:', error)
      return {
        msg: '更新扩展采购订单失败',
        code: 500,
        data: {} as PurchaseOrderExtendedDto
      }
    }
  },

  // === 采购订单审批管理 ===

  // 提交采购订单审批
  async submitPurchaseOrderForApproval(id: number): Promise<ApiResult<boolean>> {
    try {
      const response = await api.post(`/PurchaseOrder/${id}/submit`)
      return response.data
    } catch (error: any) {
      console.error('提交采购订单审批失败:', error)
      return {
        msg: '提交采购订单审批失败',
        code: 500,
        data: false
      }
    }
  },

  // 撤回采购订单
  async withdrawPurchaseOrder(id: number): Promise<ApiResult<boolean>> {
    try {
      const response = await api.post(`/PurchaseOrder/${id}/withdraw`)
      return response.data
    } catch (error: any) {
      console.error('撤回采购订单失败:', error)
      return {
        msg: '撤回采购订单失败',
        code: 500,
        data: false
      }
    }
  },

  // 审批采购订单
  async approvePurchaseOrder(id: number, decision: ApprovalDecisionDto): Promise<ApiResult<boolean>> {
    try {
      const response = await api.post(`/PurchaseOrder/${id}/approve`, decision)
      return response.data
    } catch (error: any) {
      console.error('审批采购订单失败:', error)
      return {
        msg: '审批采购订单失败',
        code: 500,
        data: false
      }
    }
  },

  // 获取采购订单审批流程
  async getPurchaseOrderApprovalFlow(id: number): Promise<ApiResult<ApprovalFlowDto>> {
    try {
      const response = await api.get(`/PurchaseOrder/${id}/approval-flow`)
      return response.data
    } catch (error: any) {
      console.error('获取采购订单审批流程失败:', error)
      return {
        msg: '获取采购订单审批流程失败',
        code: 500,
        data: {} as ApprovalFlowDto
      }
    }
  },

  // === 采购订单统计 ===

  // 获取采购订单统计数据
  async getPurchaseOrderStatistics(startDate?: string, endDate?: string): Promise<ApiResult<any>> {
    try {
      const params = new URLSearchParams()
      if (startDate) params.append('startDate', startDate)
      if (endDate) params.append('endDate', endDate)

      const response = await api.get(`/PurchaseOrder/statistics?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取采购订单统计失败:', error)
      return {
        msg: '获取采购订单统计失败',
        code: 500,
        data: {}
      }
    }
  },

  // 导出采购订单
  async exportPurchaseOrders(query: PurchaseOrderExtendedQueryDto): Promise<ApiResult<Blob>> {
    try {
      const response = await api.post('/PurchaseOrder/export', query, {
        responseType: 'blob'
      })
      // 后端返回byte[]，axios会自动转换为Blob
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      return {
        msg: '导出成功',
        code: 200,
        data: blob
      }
    } catch (error: any) {
      console.error('导出采购订单失败:', error)
      return {
        msg: '导出采购订单失败',
        code: 500,
        data: new Blob()
      }
    }
  },

  // 获取待审批单据统计数据
  async getApprovalStatistics(): Promise<ApiResult<any>> {
    try {
      const response = await api.get('/Dashboard/approval-statistics')
      return response.data
    } catch (error: any) {
      console.error('获取待审批单据统计失败:', error)
      return {
        msg: '获取待审批单据统计失败',
        code: 500,
        data: {}
      }
    }
  }
}

export default consoleApi 